import { getToken, setToken, removeToken } from '@/utils/auth'
import { SysLogin, sysProfile, sysUser } from '@/api'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  // ...其他
  // 设置token
  SET_TOKEN (state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  // 删除token
  REMOVE_TOKEN (state) {
    state.token = ''
    removeToken()
  },
  //*********************************** * 设置userInfo
  SET_USERINFO (state, value) {
    state.userInfo = value
  },
  REMOVE_USERINFO (state) {
    state.userInfo = {}
  }
}

const actions = {
  // 封装-登录逻辑
  async locationActions ({ commit }, data) {
    const res = await SysLogin(data)
    // console.log(res)
    // 当前在模块内不需加载模块名
    commit('SET_TOKEN', res.data)
    console.log('登录成功')
    return res // 把结果返回到调用处
    // async函数return的值
    // 只要不是Promise.reject()
    // 都是成功的值->返回给调用处的
    // Promise对象内(那边得用await/then取这个return的值)
  },
  // 封装-获取用户基本信息
  async userInfoActions ({ commit }) {
    const { data: userObj } = await sysProfile()

    const { data: photoObj } = await sysUser(userObj.userId)
    console.log('1', userObj, photoObj)
    //  把两次获取到的基本用户信息都添加到userInfo里面
    commit('SET_USERINFO', { ...userObj, ...photoObj })
    return userObj.roles.menus
  },

  // 封装-退出登录逻辑
  async loginOutActions ({ commit }) {
    commit('REMOVE_TOKEN')
    commit('REMOVE_USERINFO')
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
